-- Copyright (c) 2025 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
--
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local custom_msg = require 'messages.custom'
local log = require 'mc.logging'
local os = require 'os'
local DATE_LENGTH <const> = 19
local m = {}

function m.parse_date_to_timestamp(date)
    local year, month, day, hour, min, sec = date:match("^(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)$")
    local date_time_table = {
        year = tonumber(year),
        month = tonumber(month),
        day = tonumber(day),
        hour = tonumber(hour),
        min = tonumber(min),
        sec = tonumber(sec)
    }
    local timestamp = os.time(date_time_table)
    if not timestamp then
        log:error('Parse date[%s] to timestamp failed.', date)
    end
    return tostring(timestamp)
end

function m.get_timestamp(date_time)
    local date = string.sub(date_time, 1, DATE_LENGTH)
    local timestamp = m.parse_date_to_timestamp(date)
    if timestamp == nil then
        error(custom_msg.InvalidValue(date, 'DateTime'))
    end
    return timestamp
end

return m